<template>
  <div class="platformCopywriting">
    <div class="copywritingNav">
      <div class="copywritingNav_content">
        <div class="copywritingNav_content_list" v-for="(item, index) in items" :key="index"
             :class="{active: item.active}">
          <div class="content_list_title" @click="toggleActive(item.id)">
            <div class="list_title_left"><span><img :src="item.picture"/><img :src="item.picture"/></span>{{
                item.name
              }}
            </div>
            <div class="list_title_right"><i class="el-icon-arrow-down"></i></div>
          </div>
          <div class="content_list_down" v-show="item.active">
            <a :href="listItem.link" v-for="(listItem, listIndex) in item.lists" :key="listIndex" class="list_down_li"
               :class="{active: listItem.active}" @click="toggleListItemActive(item.id, listItem.id)">
              <img v-if="listItem.picture" :src="listItem.picture"/>
              {{ listItem.name }}
            </a>
          </div>
        </div>
      </div>
    </div>
    <div class="platformCopywriting_right">
      <div class="platformCopywriting_right_output">
        <div class="right_output_top">
          <div class="right_output_title">
            <div class="output_title_dd"><img :src="data.picture"/>{{ data.name }}</div>
            <div class="output_title_dt">{{data.describe}}</div>
          </div>


          <div class="right_output_content">

            <div class="output_content_list" v-if="data.is_language">
              <div class="content_list_dd">输出语言</div>
              <div class="content_list_dt">
                <el-select v-model="form.language" placeholder="请选择国家">
                  <el-option
                      v-for="country in countries"
                      :key="country"
                      :label="country"
                      :value="country"
                  >
                    <span>{{ country }}</span>
                  </el-option>
                </el-select>
              </div>
            </div>

            <div class="output_content_list" v-if="data.is_tone">
              <div class="content_list_dd">输出语气</div>
              <div class="content_list_dt">
                <el-select v-model="form.tone" placeholder="请选择语气">
                  <el-option
                      v-for="tone in tones"
                      :key="tone"
                      :label="tone"
                      :value="tone"
                  >
                    <span>{{ tone }}</span>
                  </el-option>
                </el-select>
              </div>
            </div>

            <template v-for="item in fields">
              <div class="output_content_list" v-if="item[2]==='text'">
                <div class="content_list_dd">{{ item[1] }}<span>*</span></div>
                <div class="content_list_dt">
                  <el-input v-model="form[item[0]]" :placeholder="item[3]"></el-input>
                </div>
              </div>
              <div class="output_content_list" v-else>
                <div class="content_list_dd">{{ item[1] }}<span>*</span></div>
                <div class="content_list_dt">
                  <el-input
                      type="textarea"
                      :autosize="{ minRows: 4, maxRows: 6}"
                      :placeholder="item[3]"
                      v-model="form[item[0]]">
                  </el-input>
                </div>
              </div>
            </template>


            <div class="output_content_generate">
              <div class="content_list_dd">生成条数：</div>
              <div class="content_list_dt">
                <div class="list_dt_li" :class="{ active: generateIndex === 0 }" @click="changeActive(0,1)">1</div>
                <div class="list_dt_li" :class="{ active: generateIndex === 1 }" @click="changeActive(1,2)">2</div>
                <div class="list_dt_li" :class="{ active: generateIndex === 2 }" @click="changeActive(2,3)">3</div>
              </div>
            </div>
          </div>
        </div>
        <div class="right_output_bottom">
          <div class="right_output_submit" @click="generate(); changeTab(1)" v-if="no_pending">{{infos.length ? '再次生成' : '生成'}}</div>
            <el-button type="primary" class="right_output_submit" @click="changeTab(1)"  v-if="!no_pending" :loading="true">生成中</el-button>

          <div class="right_output_hint"><img src="@a/img/sv47.svg"/>对获取的结果不满意？尝试重新修改描述</div>
        </div>
      </div>
      <div class="platformCopywriting_right_content">
        <div class="right_content_Nav">
          <div class="content_Nav_padding">
            <div class="content_Nav_list" @click="changeTab(1)" :class="{ active: activeTab === 1 }">
              全部（{{ infos.length }}）
            </div>
            <div class="content_Nav_list" @click="changeTab(2)" :class="{ active: activeTab === 2 }">
              已保存（{{ userData.length }}）
            </div>
          </div>
        </div>
        <div class="right_content_txt">
          <div class="content_txt_all" v-if="activeTab == 1">
            <div class="content_txt_list" v-for="(info, index) in infos" >
              <div class="txt_list_btn">
                <div class="list_btn_li" v-if="!info.active" @click="handleTextareaShow(index,info)"><span><img
                    src="@a/img/sv43.svg"/><img src="@a/img/sv43on.svg"/></span></div>
                <div class="list_btn_li" v-if="!info.active" @click="handleCollect(index,info)"
                     :class="{active: info.id}"><span><img src="@a/img/sv44.svg"/><img
                    src="@a/img/sv44on.svg"/></span></div>
                <div class="list_btn_li" v-if="!info.active" @click="handleCopy(index,info)"><span><img
                    src="@a/img/sv45.svg"/><img src="@a/img/sv45on.svg"/></span></div>
                <div class="list_btn_li" v-if="!info.active" @click="handleDelete(index,info)"><span><img
                    src="@a/img/sv46.svg"/><img src="@a/img/sv46on.svg"/></span></div>
                <div class="list_btn_Sure" v-if="info.active" @click="handleTextareaHide(index,info)">确定</div>
              </div>
              <div class="txt_list_describe">
                <markdown-it-vue-light class="list_describe_top" :content="info.result_content"/>
                <textarea class="list_describe_input" ref="input" v-show="info.active" v-model="info.result_content"></textarea>
              </div>
              <div class="txt_list_character">{{ info.result_content.length }}字 / {{ info.result_content.replace(/[\u4e00-\u9fa5]/g, "**").length }}字符</div>
            </div>
            <div class="not_data not_data3" v-show="infos.length === 0">
              <div class="not_data_icon"><img src="@a/img/bn28.png"/></div>
            </div>
          </div>
          <div class="content_txt_all" v-if="activeTab == 2">
            <div class="content_txt_list" v-for="(info, index) in userData" >
              <div class="txt_list_btn">
                <div class="list_btn_li" v-if="!info.active" @click="handleTextareaShow(index,info)"><span><img
                    src="@a/img/sv43.svg"/><img src="@a/img/sv43on.svg"/></span></div>
<!--                <div class="list_btn_li" v-if="!info.active" @click="handleCollect(index,info)"-->
<!--                     :class="{active: info.id}"><span><img src="@a/img/sv44.svg"/><img-->
<!--                    src="@a/img/sv44on.svg"/></span></div>-->
                <div class="list_btn_li" v-if="!info.active" @click="handleCopy(index,info)"><span><img
                    src="@a/img/sv45.svg"/><img src="@a/img/sv45on.svg"/></span></div>
                <div class="list_btn_li" v-if="!info.active" @click="handleDelete(index,info)"><span><img
                    src="@a/img/sv46.svg"/><img src="@a/img/sv46on.svg"/></span></div>
                <div class="list_btn_Sure" v-if="info.active" @click="handleTextareaHide(index,info)">确定</div>
              </div>
              <div class="txt_list_describe">
                <markdown-it-vue-light class="list_describe_top" :content="info.result_content"/>
                <textarea class="list_describe_input" ref="input" v-show="info.active" v-model="info.result_content "></textarea>
              </div>
              <div class="txt_list_character">{{ info.result_content.length }}字 / {{ info.result_content.replace(/[\u4e00-\u9fa5]/g, "**").length }}字符</div>
            </div>
            <div class="not_data not_data3" v-show="userData.length === 0">
              <div class="not_data_icon"><img src="@a/img/bn28.png"/></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 充值弹窗 -->
    <rechargeWindow v-if="rechargeShow" @close="rechargeShow = false"></rechargeWindow>
  </div>
</template>


<script>
import {MessageBox, Message} from 'element-ui';
import NProgress from "nprogress";
import rechargeWindow from "@c/common/rechargeWindow/rechargeWindow";
import MarkdownItVueLight from 'markdown-it-vue/dist/markdown-it-vue-light.umd.min.js'
import 'markdown-it-vue/dist/markdown-it-vue-light.css'



export default {
  name: "platformCopywriting",
  data() {
    return {
      rechargeShow: false,
      no_pending: true,
      all_num: 0,
      complete_num: 0,
      form: {
        generated_quantity: 1,
        copywriting_id: 0,
      },
      selectedCountry: '', // 选中的国家代码
      countries: [
      ],
      tones: [],
      data: {},
      userData: [],
      fields: [],
      value2: 3,
      outputSummary: '',
      activeTab: 1,
      outputTitle: '',
      items: [],
      infos: [],
      generateIndex:0,
    };
  },
  methods: {
    changeActive(index, value) {
      this.generateIndex = index;
      this.form.generated_quantity = value;
    },
    generate() {
      this.no_pending = false;
      this.all_num = this.form.generated_quantity;
      this.complete_num = 0;
      let that = this;
      this.axios.post('/api/copywriting/getAccess', this.form).then(res => {
        if (res.code === 1) {
          if (that.$store.getters.isLogin) {
            that.axios.get('/api/member/getInfo').then(res => {
              localStorage.setItem('memberInfo', JSON.stringify(res.result))
              that.$store.commit('setMemberInfo', res.result)
            })
          }


          that.key = res.result.key

          let key = res.result.key;
          let len = res.result.form.generated_quantity;
          for (let i = 0; i < len; i++) {
            that.infos.unshift({
              id: 0,
              active: false,
              result_content: '',
              wordCount: 0,
              charCount: 0,
              form: res.result.form
            })
            let source = new EventSource(that.baseURL + `/api/common/generateCopywriting?key=${key}&event_name=chatgpt${i}`);

            //监听test事件
            source.addEventListener('chatgpt' + i, function (event) {
              if (event.data) {
                if (event.data === 'end') {
                  that.loading = false;
                  source.close()
                  that.complete_num ++;
                  if(that.complete_num >= that.all_num) {
                    that.no_pending = true;
                  }
                } else {
                  let res = event.data
                  res = JSON.parse(res)
                  that.infos[i].result_content += res.title
                }
              }

            });
          }
        } else {
          that.generated_quantity = 0;
          that.no_pending = true;
          if (res.result && res.result.action) {
            let action = res.result.action;
            if (action === 'recharge') {
              that.rechargeShow = true;
            }
            if (action === 'login') {
              that.showLogin = true;
            }
          }
        }
      })
    },
    onExampleClick(title, summary) {
      // 将示例中的标题和摘要内容分别绑定到对应的输入框中
      this.outputTitle = title;
      this.outputSummary = summary;
    },
    //选项卡切换
    changeTab(index) {
      this.activeTab = index;
    },
    //编辑按钮
    handleTextareaShow(index, info) {
      // 将点击项的 active 属性设置为 true，显示文本框并将光标对齐获取焦点
      info.active = true;
      this.userData = JSON.parse(JSON.stringify(this.userData))
      this.userData = JSON.parse(JSON.stringify(this.info))
      this.$nextTick(() => {
        this.$refs.input[index].focus();
      });
    },
    handleTextareaHide(index, info) {
      // 将点击项的 active 属性设置为 false，隐藏文本框
      info.active = false;
      let that = this;
      if (info.id) {
        this.axios.post('/api/copywritingMember/update', {id: info.id, result_content: info.result_content}).then(res => {
          if(res.code === 1) {
            that.getCollectList()
          }
        })
      }
    },
    //收藏按钮
    handleCollect(index,info) {
      let that = this;
      if (info.id) {
        this.axios.post('/api/copywritingMember/delete', {id: info.id}).then(res => {
          if(res.code === 1) {
            info.id = 0;
            that.getCollectList()
            that.$message({
              message: '已取消收藏',
              type: 'success'
            });
          }
        })

      } else {
        this.axios.post('/api/copywritingMember/add', {
          copywriting_id: that.$route.query.id,
          result_content: info.result_content,
          form: info.form
        }).then(res => {
          if(res.code === 1) {
            info.id = res.result.id;
            that.getCollectList()
            that.$message({
              message: '已收藏',
              type: 'success'
            });
          }
        })

      }
    },

    getCollectList(){
      let that = this;
      this.axios.post('/api/copywritingMember/list',{'copywriting_id': that.$route.query.id}).then(res => {
        if(res.code === 1) {
          that.userData = res.result;
        }
      })
    },
    //复制按钮
    handleCopy(index,info) {
      const el = document.createElement('textarea');
      el.value = info.result_content;
      el.setAttribute('readonly', '');
      el.style.position = 'absolute';
      el.style.left = '-9999px';
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
      this.$message({
        message: '已复制',
        type: 'success'
      });
    },
    //删除按钮
    handleDelete(index, info) {
      let that = this;
      MessageBox.confirm(`确定删除此条信息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
// 用户点击确定后执行删除操作

        if (info.id) {
          this.axios.post('/api/copywritingMember/delete', {id: info.id}).then(res => {
            if(res.code === 1) {
              info.id = 0;
              this.infos.splice(index, 1);
              that.getCollectList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          })
        }else{
          this.infos.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
        that.getCollectList()


      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
        // 用户点击取消或者弹窗关闭时不做任何操作
      });
    },
    //下拉点击效果
    toggleActive(id) {
      this.items.forEach(i => {
        if (i.id != id) {
          i.active = false;
        } else if (i.active) { // 判断当前 item 是否已经是 active 状态
          i.active = false;
        } else {
          i.active = true;
        }
      });
    },
    toggleListItemActive(cat_id, id) {
      let item = null;

      for (let i in this.items){
        if(this.items[i].id == cat_id) {
          item = this.items[i];
          break;
        }
      }


      item.lists.forEach((listItem) => {
        if (id == listItem.id) {
          listItem.active = true;
        } else {
          listItem.active = false;
        }
      });
      let url = '/copyWriting?catid=' + cat_id + '&id=' + id;
      if (url !== this.$route.path){

        this.$router.push({
          path: url,
        })
        this.getProduct(this.$route.query.id)
      }


    },
    getProduct(id) {
      let that = this;
      that.axios.post('/api/copywriting/getData', {id: id}).then(
          res => {
            if (res.code === 1) {
              document.title =  res.result.data.name  + '-' + "AiDOG";
              that.data = res.result.data;

              that.userData = res.result.user_data;
              that.fields = res.result.fields;
              that.tones = res.result.tones;
              that.infos = []
              that.no_pending = true;
              that.form = {
                generated_quantity: 1,
                copywriting_id: id,
              };
              if (that.data.is_language) {
                that.form.language = '中文';
                that.form = JSON.parse(JSON.stringify(that.form))
              }
            }
          }
      )
    },
    getList() {
      let that = this;
      that.axios.post('/api/copywriting/getList').then(res => {
        if (res.code === 1) {
          that.items = res.result
          that.toggleActive(that.$route.query.catid)
          that.toggleListItemActive(that.$route.query.catid,that.$route.query.id)
        }
      })
    },
  },
  components: {
     rechargeWindow,
    MarkdownItVueLight
  },

  mounted() {
    this.getList()
    this.getProduct(this.$route.query.id)
  },
  created() {
    if(!this.$route.query.id){
      this.$router.replace({
        'path' : '/copyWriting?catid=1&id=2'
      })
    }

    let that = this;
    that.axios.post('/api/copywriting/getLanguage').then(
        res => {
          if(res.code === 1) {
            that.countries = res.result;
          }
        }
    )
  }
}
</script>

<style>
@import "platformCopywriting.css";
</style>
